﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Detail.DeepProcessing;
using Traceability.App.Model.DeepProcessing;
using Traceability.App.Model.Slaughter;
using Traceability.App.Model;
using Traceability.App.InfrasIntructure;
using Traceability.App.ErrorCount;

public class AddDeepProcessingCompanyHandler : IRequestHandler<AddDeepProcessingCompanyCommand, ApiResult<int>>
{
    private readonly IBaseRepository<DeepProcessingCompanyModel> _deepcomRepo;
    private readonly IBaseRepository<BasicModel> _basicRepo;
    private readonly IBaseRepository<SlaughterCommpanyModel> _slauComRepo;
    private readonly IMapper _mapper;
    private readonly TraceabilityDbContext db;

    public AddDeepProcessingCompanyHandler(
        IBaseRepository<DeepProcessingCompanyModel> deepcomRepo,
        IBaseRepository<BasicModel> basicRepo,
        IBaseRepository<SlaughterCommpanyModel> slauComRepo,
        IMapper mapper,
        TraceabilityDbContext db)
    {
        _deepcomRepo = deepcomRepo;
        _basicRepo = basicRepo;
        _slauComRepo = slauComRepo;
        _mapper = mapper;
        this.db = db;
    }

    public async Task<ApiResult<int>> Handle(AddDeepProcessingCompanyCommand request, CancellationToken cancellationToken)
    {
        var res = new ApiResult<int>();

        // 使用事务确保所有操作要么全部成功，要么全部失败
        using var transaction = await db.Database.BeginTransactionAsync();

        try
        {
            // 1. 添加深加工企业信息
            var model = _mapper.Map<DeepProcessingCompanyModel>(request);
            var deepComId = await _deepcomRepo.Add(model);

            if (deepComId <= 0)
            {
                throw new Exception("添加深加工企业信息失败");
            }

            // 2. 更新BasicModel表
            var basicModel =  _basicRepo.GetAll().Where(b => b.Batch == request.Batch).FirstOrDefault();
            if (basicModel != null)
            {
                basicModel.License = request.LicenseNum;
                await _basicRepo.Update(basicModel);
            }

            // 3. 更新SlaughterCompanyModel表
            var slaughterModel =  _slauComRepo.GetAll().Where(s => s.Batch == request.Batch).FirstOrDefault();
            if (slaughterModel != null)
            {
                slaughterModel.CompanyName = request.CompanyName;
                await _slauComRepo.Update(slaughterModel);
            }

            // 提交事务
            await transaction.CommitAsync();

            res.Code = ApiEnum.Success;
            res.Msg = "添加深加工企业信息并更新相关表成功";
            res.Datas = deepComId;
        }
        catch (Exception ex)
        {
            // 回滚事务
            await transaction.RollbackAsync();

            res.Code = ApiEnum.Fail;
            res.Msg = $"操作失败: {ex.Message}";
            res.Datas = 0;
        }

        return res;
    }
}